/*
 * Copyright 2018-2021 guerlab.net and other contributors.
 *
 * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, Version 3 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.guerlab.spring.mybatis.typehandlers;

import com.fasterxml.jackson.databind.ObjectMapper;
import net.guerlab.smart.pay.core.domain.PayLogExtends;
import net.guerlab.spring.commons.util.SpringApplicationContextUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 扩展信息表类型处理
 *
 * @author guer
 */
@SuppressWarnings("WeakerAccess")
public class PayLogExtendsTypeHandler extends BaseTypeHandler<PayLogExtends> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, PayLogExtends parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, toJson(parameter));
    }

    @Override
    public PayLogExtends getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return toObject(rs.getString(columnName));
    }

    @Override
    public PayLogExtends getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return toObject(rs.getString(columnIndex));
    }

    @Override
    public PayLogExtends getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return toObject(cs.getString(columnIndex));
    }

    private ObjectMapper objectMapper() {
        return SpringApplicationContextUtil.getContext().getBean(ObjectMapper.class);
    }

    private String toJson(PayLogExtends object) {
        try {
            return objectMapper().writeValueAsString(object);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private PayLogExtends toObject(String content) {
        if (StringUtils.isBlank(content)) {
            return null;
        }

        try {
            return objectMapper().readValue(content, PayLogExtends.class);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
